package zhibi.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import zhibi.commons.exception.MessageException;
import zhibi.domain.Member;
import zhibi.domain.Orders;
import zhibi.domain.ScoreLog;
import zhibi.extra.base.BaseServiceImpl;
import zhibi.extra.pojo.OrdersPo;
import zhibi.frame.domain.Page;
import zhibi.frame.mybatis.example.Example;
import zhibi.mapper.MemberMapper;
import zhibi.mapper.OrdersMapper;
import zhibi.mapper.ScoreLogMapper;
import zhibi.service.OrdersService;

import java.util.Date;

/**
 * Created by 执笔 on 2018/3/24.
 */
@Service
@Transactional
public class OrdersServiceImpl extends BaseServiceImpl<Orders> implements OrdersService {

    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private ScoreLogMapper scoreLogMapper;

    @Autowired
    public OrdersServiceImpl(OrdersMapper mapper) {
        super(mapper);
    }

    @Override
    public PageInfo<OrdersPo> selectPoByExample(Example example, Page page) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return new PageInfo<>(ordersMapper.selectPoByExample(example), 5);
    }

    @Override
    public void balance(Integer id, Double balance) {
        Orders orders = ordersMapper.selectByPrimaryKey(id);
        if (orders == null) throw new MessageException("该出行不存在");
        Double oldBlance = orders.getBalance();
        orders.setBalance(balance);
        //orders.setStatus("success");
        orders.setProfit(orders.getPrice() - orders.getBalance());
        ordersMapper.updateByPrimaryKeySelective(orders);

        if (oldBlance == null || oldBlance == 0) {
            double score = orders.getPrice() / 100;
            //修改积分
            Member member = memberMapper.selectByPrimaryKey(orders.getMemberid());
            if (member != null) {
                Double score1 = member.getScore();
                if (score1 == null) score1 = 0D;
                member.setScore(score1 + score);
                memberMapper.updateByPrimaryKeySelective(member);
                //积分记录
                ScoreLog scoreLog = new ScoreLog();
                scoreLog.setOrdersid(id);
                scoreLog.setMemberid(member.getId());
                scoreLog.setAddtime(new Date());
                scoreLog.setValue(score);
                scoreLogMapper.insertSelective(scoreLog);
            }
        }

    }
}
